package analysis

import (
	"encoding/json"
	"github.com/cihub/seelog"
	"irisysFtp/conf"
	"irisysFtp/db"
	"log"
	"net/http"
	"strings"
	"time"
)

func SendAndSave(deviceFlow []*db.DeviceFlow) (bool, error) {
	sendModel := make(map[string]*db.SendModel)
	for _, val := range deviceFlow {
		//2006-01-02 15:04:05
		date := val.Time.Format("2006-01-02")
		time := val.Time.Format("15:04:05")
		inout := db.InOut{
			Zone:      val.Zone,
			Date:      date,
			StartTime: time,
			EndTime:   time,
			Enter:     val.CountEnter,
			Exit:      val.CountExit,
			Time:      val.Time,
		}
		if sendModel[val.DeviceId] == nil {
			sendModel[val.DeviceId] = &db.SendModel{
				DeviceId:   val.DeviceId,
				DeviceType: val.DeviceType,
				IpAddress:  val.IpAddress,
			}
		}
		sendModel[val.DeviceId].InOutMetrics = append(sendModel[val.DeviceId].InOutMetrics, inout)
	}

	insertLen := 0

	for _, val := range sendModel {
		if data, err := json.Marshal(val); err == nil {
			if b := HttpClient(data); !b {
				le, err := db.InsertDeviceFlowBySendModel(val)
				if err != nil {
					return false, err
				}
				insertLen += le
				seelog.Infof("tag==1 %v save  len:%v %+v", val.DeviceId, le, val)
			}
		}
	}
	return true, nil
}

func HttpClient(data []byte) bool {
	client := &http.Client{
		Timeout: time.Second * 5,
	}
	req, err := http.NewRequest("POST",
		conf.GetSenUrl(),
		strings.NewReader(string(data)))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if err != nil {
		log.Fatal(err)
	}
	if resp, err := client.Do(req); err == nil {
		code := resp.StatusCode
		if code == 200 {
			seelog.Infof("send %v code :%v ", conf.GetSenUrl(), code)
			return true
		} else {
			seelog.Errorf("send %v code :%v ", conf.GetSenUrl(), code)
		}
	} else {
		seelog.Error(err)
	}
	return false

}
